<?php
/*
 * @Descripttion: http 服务
 * @version:
 * @Author: ewgof
 * @Date: 2020-08-12 00:24:23
 * @LastEditors: ewgof
 * @LastEditTime: 2021-10-11 22:36:33
*/

use Workerman\Worker;

$db = null;
global $db;

// 创建一个Worker监听2345端口，使用http协议通讯
$http_worker = new Worker("http://0.0.0.0:2345");

// 启动4个进程对外提供服务
$http_worker->count = 4;
$http_worker->name = 'http-service';

$http_worker->onConnect = function ($connection) { };

$http_worker->onWorkerStart = function ($connection) {
    // global $db;
    // // 初始化数据库连接
    // $db = db_connect();

    // 触发一个事件
    // trigger('login', $connection->id);
    // 把一个值放进缓存
};

// 接收到浏览器发送的数据
$http_worker->onMessage = function ($connection, $request) {
    // 对请求进行路由分发
    try {
        route($connection, $request);
    } catch (\Exception $e) {
        send($connection, $e->getMessage(), $e->getCode());
    }
};


$http_worker->onWorkerStop = function ($connection) {
    global $db;
    unset($db);
};


$http_worker->onClose = function ($connection) {
    
};

// 如果不是在根目录启动，则运行runAll方法
if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
